package com.rayc.mall.core.interceptor;

import com.rayc.mall.common.context.AdminContext;
import com.rayc.mall.common.context.UserContext;
import com.rayc.mall.common.exception.UnauthorizedException;
import com.rayc.mall.core.properties.AdminProperties;
import com.rayc.mall.common.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: Ray-C
 * @CreateTime: 2025-03-23
 * @Description: 登录拦截器
 * @Version: 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final AdminProperties adminProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            // 没匹配到路径，给全局异常处理controller处理
            return true;
        }

        // 获取网关传递的user-id信息
        String userIdStr = request.getHeader("user-id");
        if (userIdStr == null) {
            throw new UnauthorizedException("未登录");
        }
        Long userId = Long.parseLong(userIdStr);
        // 存入上下文
        UserContext.setUser(userId);
        // 获取用户id，判断是否管理员
        List<Long> admins = adminProperties.getAdmins();
        AdminContext.setAdmin(CollUtils.isNotEmpty(admins) && admins.contains(userId));
        // 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理用户
        UserContext.removeUser();
    }
}
